<template>
  <div class="echartsPage">
    <div id="main"></div>
  </div>
</template>

<script setup>
import { getMapDataApi } from '@/api/system/conf'
import getOption from '@/utils/echarts/mapOptionUtil'

let geoJSON = null // 地图元素geo数据
let mapData = null // 地图data数据

let xzqhdmNow = '3205' // 苏州市
let xzqhmcNow = '苏州市' // 苏州市
let mapUrl = '苏州市.json'

const filterJsonData = (url) => {
  // 更新geoJSON
  return new Promise((resolve, reject) => {
    getMapDataApi(url)
      .then((res) => {
        resolve(res)
      })
      .catch((e) => {
        const data = geoJSON.features.find((item) => {
          return item.properties.PAC === xzqhdmNow
        })
        resolve({
          type: 'FeatureCollection',
          name: xzqhmcNow,
          features: [data],
        })
      })
  })
}
const initgeoCoordMap = (geoJSON) => {
  // 更新data
  return new Promise((resolve, reject) => {
    // 格式化mapData和convertData
    const arr = []
    // convertData = [];
    geoJSON.features.forEach((item) => {
      arr.push({
        value1: 110,
        value2: 120,
        code: item.properties.PAC,
        name: item.properties.name,
      })
      // 重置中心点
      // convertData.push({
      //     name: item.properties.name,
      //     value: [item.properties.CenterX, item.properties.CenterY, 10]
      // })
    })
    resolve(arr)
  })
}

// 渲染map
function renderMap(mapChart) {
  mapChart.showLoading({
    text: 'loading',
    color: '#c23531',
    textColor: '#000',
    maskColor: 'rgba(255, 255, 255, 0.8)',
    zlevel: 100,
    fontSize: 12,
    showSpinner: true,
    spinnerRadius: 10,
    lineWidth: 5,
  })

  filterJsonData(mapUrl)
    .then(function (data) {
      geoJSON = data // 更新geoJSON
      return initgeoCoordMap(data)
    })
    .then(function (data) {
      mapData = data // 获取mapData

      echarts.registerMap(geoJSON.name, geoJSON)

      const mapOption = getOption(geoJSON.name, mapData, xzqhdmNow)

      mapChart.hideLoading()
      mapChart.setOption(mapOption, true)
    })
}

nextTick(() => {
  const chartDom = document.getElementById('main')
  const mapChart = echarts.init(chartDom)
  mapChart.clear()

  mapChart.on('click', (params) => {
    console.log(params)
    // 点击地图导航
    if (params.componentType === 'graphic') {
      if (params.info) {
        xzqhmcNow = params.info.name
        xzqhdmNow = params.info.code
      }
    }
    // 点击地图块
    if (params.componentType === 'series') {
      xzqhmcNow = params.data.name
      xzqhdmNow = params.data.code
    }
    mapUrl = xzqhmcNow + '.json'
    renderMap(mapChart)
  })

  renderMap(mapChart)

  window.onresize = () => {
    mapChart.resize()
  }
})
</script>

<style scoped>
.echartsPage {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f1f1f1;
}
#main {
  margin: 0 auto;
  border: 1px solid #c7c7c7;
  width: 800px;
  height: 50%;
  background-color: #fff;
}
</style>
